/**
 * qccr.com Inc.
 * Copyright (c) 2014-2016 All Rights Reserved.
 */
package com.ssc.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.alibaba.fastjson.JSON;

/**
 * Ajax调用返回
 * @author wuxianji
 * @version $Id: AjaxResult.java, v 0.1 2016年4月13日 下午8:07:16 wxianji Exp $
 */
public class AjaxResult {

    private Map<String, Object> result = new HashMap<String, Object>();

    /**结果数据 */
    private Object            data;

    /** 成功 */
    private boolean           isSuccess        = true;

    /**扩展信息*/
    private String            extInfo;

    private Map<String, String> errors;

    private AjaxResult() {
    }

    private AjaxResult(boolean isSuccess) {
        if (isSuccess) {
            success();
        }else {
            failure();
        }
    }

    public static AjaxResult createSuccess() {
        return new AjaxResult(true);
    }

    public static AjaxResult createFailure() {
        return new AjaxResult(false);
    }

    public void success() {
        isSuccess = true;
    }

    public void failure() {
        isSuccess = false;
    }

    public void setInfo(String info) {
        extInfo = info;
    }

    public void setData(Object data) {
        data = data;
    }

    public void setErrorInfo(String info) {
        this.failure();
        this.setInfo(info);
    }

    public void setErrorData(BindingResult bindingResult) {
        this.failure();
        createErrors(bindingResult);
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
    }

    private Map<String, String> createErrors(BindingResult result) {

        errors = Maps.newHashMap();

        List<FieldError> list = result.getFieldErrors();
        for (FieldError error : list) {
            errors.put(error.getField(), error.getDefaultMessage());
        }
        return errors;
    }

}
